package com.udaos.modules.card.controllers;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.adaptor.WhaleAdaptor;
import org.nutz.mvc.annotation.AdaptBy;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.udaos.common.base.Globals;
import com.udaos.common.base.Result;
import com.udaos.common.page.DataTableColumn;
import com.udaos.common.page.DataTableOrder;
import com.udaos.models.card.Ud_wx_card;
import com.udaos.models.sys.Sys_user;
import com.udaos.models.wx.Wx_config;
import com.udaos.modules.card.pojo.DateInfoRange;
import com.udaos.modules.card.pojo.DateInfoTerm;
import com.udaos.modules.card.pojo.Sku;
import com.udaos.modules.card.pojo.TextImage;
import com.udaos.modules.card.pojo.UseCondition;
import com.udaos.modules.card.services.UdWxCardService;
import com.udaos.modules.card.utils.HttpUtils;
import com.udaos.modules.wx.services.WxConfigService;

import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMediaImgUploadResult;
import net.sf.json.JSONObject;

/**
 * 微信卡券WEB
 * @author Administrator
 *
 */
@IocBean
@At("/platform/wx/card")
public class UdWxCardController {
	
	@Inject
	private UdWxCardService cardInfoService;
	@Inject
	private WxConfigService wxConfigService;
	
	/**
	 * 首页
	 */
	@At("")
	@Ok("beetl:/platform/card/wx/index.html")
	@RequiresAuthentication
	public void index() {

	}
	/**
	 * 加载数据
	 * @param title
	 * @param length
	 * @param start
	 * @param draw
	 * @param order
	 * @param columns
	 * @return
	 */
	@At
	@Ok("json:full") 
	@RequiresAuthentication
	public Object data( @Param("title") String title,@Param("length") int length, @Param("start") int start,
			@Param("draw") int draw, @Param("::order") List<DataTableOrder> order,
			@Param("::columns") List<DataTableColumn> columns) {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			//获取主体
			Sys_user user = (Sys_user) subject.getPrincipal();
			String company_id=user.getUnit().getCompany_id();
			Cnd cnd = Cnd.NEW();
			cnd.and("company_id", "=", company_id);
			if (!Strings.isBlank(title))
				cnd.and("title", "like", "%" + title + "%");
			return cardInfoService.data(length, start, draw, order, columns, cnd, null);
		}else{
			return Result.error("数据加载失败");
		}
	}
	/**
	 * 新增卡券
	 * @param unitid
	 * @return
	 */
	@At
	@Ok("beetl:/platform/card/wx/add.html")
	@RequiresAuthentication
	public Object add() {
		Cnd cnd=Cnd.NEW();
		cnd.and("delFlag", "=", "0");
		List<Wx_config> wxList=wxConfigService.query(cnd);
		return wxList;
	}
	
	/**
	 * 新增
	 * @param card_info
	 * @param begin_timestamp_str
	 * @param end_timestamp_str
	 * @param request
	 * @return
	 */
	@At("/addDo")
	@Ok("json")
	@RequiresAuthentication 
	@AdaptBy(type = WhaleAdaptor.class)
	public Object addDo(String wxId,@Param("..") Ud_wx_card card_info,@Param("begin_timestamp_str") String begin_timestamp_str,@Param("end_timestamp_str") String end_timestamp_str,HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			try {
				Sys_user user = (Sys_user) subject.getPrincipal();
				//设置ID
				card_info.setId(UUID.randomUUID().toString().replaceAll("-", ""));
				//设置单位信息
				card_info.setUnitid(user.getUnitid());
				card_info.setWxid(wxId);
				//设置主体
				card_info.setCompany_id(user.getUnit().getCompany_id());
				//设置时间
				if(card_info.getType().equals("DATE_TYPE_FIX_TIME_RANGE")){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					int begin_timestamp = (int) (sdf.parse(begin_timestamp_str).getTime() / 1000);
					int end_timestamp=(int) (sdf.parse(end_timestamp_str).getTime() / 1000);
					
					card_info.setBegin_timestamp(begin_timestamp);
					card_info.setEnd_timestamp(end_timestamp);
				}else{
					//设置失效时间
					 long time = System.currentTimeMillis();  
				     Date d = new Date(time);  
				     Calendar c = Calendar.getInstance();  
				     c.setTime(d);  
				     c.add(Calendar.DAY_OF_MONTH, card_info.getFixed_term());  
				     card_info.setEnd_timestamp((int)(c.getTimeInMillis()/1000));
				}
				//设置创建时间
				card_info.setCreate_time((int) (System.currentTimeMillis() / 1000));
				
				// 2 进行数据组装
				// 获取微信相关信息
				WxMpService wxMpService=getWxMpService(wxId);
				// 上传logo
				File logoFile=new File(Globals.AppUploadPath+card_info.getLogo_url());//DownloadURLFileUtils.downloadFromUrl(logoUrl, UUID.randomUUID().toString(), card_info.getLogo_url().split("\\.")[1]) ;
				WxMediaImgUploadResult result=wxMpService.getMaterialService().mediaImgUpload(logoFile);
				String logo_url=result.getUrl();
				
				//2.1 组装基本信息
				Map<String,Object> base_info=new HashMap<String,Object>();
				base_info.put("logo_url", logo_url);
				base_info.put("brand_name", card_info.getBrand_name());
				base_info.put("code_type", card_info.getCode_type());
				// 判断是否为自定义code_type
				if(card_info.getCode_type().equals("CODE_TYPE_NONE")){
					base_info.put("center_title", card_info.getCenter_title());
					base_info.put("center_sub_title", card_info.getCenter_sub_title());
					base_info.put("center_url", card_info.getCenter_url());
					
					base_info.put("custom_url_name", card_info.getCustom_url_name());
					base_info.put("custom_url_sub_title", card_info.getCustom_url_sub_title());
					base_info.put("custom_url", card_info.getCustom_url());
					
					base_info.put("promotion_url_name", card_info.getPromotion_url_name());
					base_info.put("promotion_url_sub_title", card_info.getPromotion_url_sub_title());
					base_info.put("promotion_url", card_info.getPromotion_url());
				}
				base_info.put("title", card_info.getTitle());
				base_info.put("sub_title", card_info.getSub_title());
				base_info.put("color", card_info.getColor());
				base_info.put("notice", card_info.getNotice());
				base_info.put("service_phone", card_info.getService_phone());
				base_info.put("description", card_info.getDescription());
				//  组装使用时间
				if(card_info.getType().equals("DATE_TYPE_FIX_TIME_RANGE")){
					//时间段
					DateInfoRange dateInfoRange=new DateInfoRange();
					dateInfoRange.setType("DATE_TYPE_FIX_TIME_RANGE");
					dateInfoRange.setBegin_timestamp(card_info.getBegin_timestamp());
					dateInfoRange.setEnd_timestamp(card_info.getEnd_timestamp());
					base_info.put("date_info", dateInfoRange);
				}else{
					//时长
					DateInfoTerm dateInfoTerm=new DateInfoTerm();
					dateInfoTerm.setType("DATE_TYPE_FIX_TERM");
					dateInfoTerm.setFixed_term(card_info.getFixed_term());
					dateInfoTerm.setFixed_begin_term(0);
					dateInfoTerm.setEnd_timestamp(card_info.getEnd_timestamp());
					base_info.put("date_info", dateInfoTerm);
				}
				// 库存
				Sku sku=new Sku();
				sku.setQuantity(card_info.getQuantity());
				base_info.put("sku", sku);
				//每人领取张数
				base_info.put("get_limit", card_info.getGet_limit());
				base_info.put("source", card_info.getSource());
				base_info.put("use_custom_code", false);
				base_info.put("bind_openid", false);
				base_info.put("can_share", card_info.isCan_share());
				base_info.put("can_give_friend", card_info.isCan_give_friend());
				
				//2.2设置高级信息
				Map<String,Object> advanced_info=new HashMap<String,Object>();
				// 使用门槛（条件）字段
				UseCondition condition=new UseCondition();
				//判断卡券类型
				if(card_info.getCard_type().equals("CASH")){
					if(null !=card_info.getAccept_category()){
						condition.setAccept_category(card_info.getAccept_category());
					}
					condition.setReject_category(card_info.getReject_category());
					condition.setLeast_cost(card_info.getLeast_cost());
					
				}
				if(card_info.getCard_type().equals("GIFT")){
					condition.setLeast_cost(card_info.getLeast_cost());
					condition.setObject_use_for(card_info.getObject_use_for());
				}
				condition.setCan_use_with_other_discount(card_info.getCan_use_with_other_discount());
				advanced_info.put("use_condition", condition);
				
				// 封面摘要结构体
				Map<String,Object> abstract1=new HashMap<String,Object>();
				File getIcon_url_listFile=new File(Globals.AppUploadPath+card_info.getIcon_url_list());//DownloadURLFileUtils.downloadFromUrl(Icon_url_listUrl, UUID.randomUUID().toString(), card_info.getIcon_url_list().split("\\.")[1]) ;
				WxMediaImgUploadResult result1=wxMpService.getMaterialService().mediaImgUpload(getIcon_url_listFile);
				String getIcon_url_list=result1.getUrl();
				String [] url_list={getIcon_url_list};
				abstract1.put("abstract",card_info.getAbstractStr());
				abstract1.put("icon_url_list",url_list);
				advanced_info.put("abstract", abstract1);
				
				List<TextImage> text_image_list=new ArrayList<TextImage>();
				
				TextImage textImage=new TextImage();
				File Image_urlFile=new File(Globals.AppUploadPath+card_info.getImage_url());//DownloadURLFileUtils.downloadFromUrl(Image_url, UUID.randomUUID().toString(), card_info.getImage_url().split("\\.")[1]) ;
				WxMediaImgUploadResult result2=wxMpService.getMaterialService().mediaImgUpload(Image_urlFile);
				String image_url=result2.getUrl();
				textImage.setImage_url(image_url);
				textImage.setText(card_info.getText());
				text_image_list.add(textImage);
				
				if(!Strings.isBlank(card_info.getImage_url1())){
					TextImage textImage1=new TextImage();
					File Image_url1File=new File(Globals.AppUploadPath+card_info.getImage_url1());//DownloadURLFileUtils.downloadFromUrl(Image_url1, UUID.randomUUID().toString(), card_info.getImage_url1().split("\\.")[1]) ;
					WxMediaImgUploadResult result21=wxMpService.getMaterialService().mediaImgUpload(Image_url1File);
					String image_url1=result21.getUrl();
					textImage1.setImage_url(image_url1);
					textImage1.setText(card_info.getText1());
					text_image_list.add(textImage1);
				}
				if(!Strings.isBlank(card_info.getImage_url2())){
					TextImage textImage2=new TextImage();
					File Image_url2File=new File(Globals.AppUploadPath+card_info.getImage_url2());//DownloadURLFileUtils.downloadFromUrl(Image_url2, UUID.randomUUID().toString(), card_info.getImage_url2().split("\\.")[1]) ;
					WxMediaImgUploadResult result22=wxMpService.getMaterialService().mediaImgUpload(Image_url2File);
					String image_url2=result22.getUrl();
					textImage2.setImage_url(image_url2);
					textImage2.setText(card_info.getText2());
					text_image_list.add(textImage2);
				}
				
				advanced_info.put("text_image_list", text_image_list);
				
				Map<String,Object> group=new HashMap<String,Object>();
				group.put("base_info", base_info);
				group.put("advanced_info", advanced_info);
				//判断类型
				if(card_info.getCard_type().equals("GROUPON")){
					//团购
					group.put("deal_detail", card_info.getRemark());
				}else if(card_info.getCard_type().equals("CASH")){
					//代金券
					group.put("least_cost", 0);
					group.put("reduce_cost", card_info.getCard_fee()*100);
				}else if(card_info.getCard_type().equals("DISCOUNT")){
					//折扣券
					group.put("discount", card_info.getRemark());
				}else if(card_info.getCard_type().equals("GIFT")){
					//兑换券
					group.put("gift", card_info.getRemark());
				}else{
					//优惠券
					group.put("default_detail", card_info.getRemark());
				}
				Map<String,Object> param=new HashMap<String,Object>();
				param.put("card_type", card_info.getCard_type());
				param.put(card_info.getCard_type().toLowerCase(), group);
				Map<String,Object> card=new HashMap<String,Object>();
				card.put("card", param);
				// 3.创建卡券
				String token=wxMpService.getAccessToken();
				String url="https://api.weixin.qq.com/card/create?access_token="+token;
				System.out.println(JSONObject.fromObject(card).toString());
				JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", JSONObject.fromObject(card).toString());
				System.err.println(jsonObject);
				/*"errcode":0,"errmsg":"ok","card_id":"pqDfiw2J7DGvJjw-vtZ2Y4gaD8Ho"*/
				if(jsonObject.getInt("errcode")==0){
					
					card_info.setCard_id(jsonObject.getString("card_id"));
					card_info.setState("0");
			
					//保存卡券
					cardInfoService.insertCard(card_info);
					
					return Result.success("保存成功");
				}
				
				return Result.error("保存失败");
			}catch (Exception e) {
				return Result.error(e.getMessage());
			}
		}
		return Result.error("保存失败");
	}
	
	
	/**
	 * 详情
	 * @param id
	 * @return
	 */
	@At("/detail/?")
	@Ok("beetl:/platform/card/wx/edit.html")
	@RequiresAuthentication
	public Object detail(String id) {
		Map<String,Object> map=new HashMap<String,Object>();
		if (!Strings.isBlank(id)) {
			Ud_wx_card card_info = cardInfoService.fetch(id);
			map.put("card_info", card_info);
	    }
		Cnd cnd=Cnd.NEW();
		cnd.and("delFlag", "=", "0");
		List<Wx_config> wxList=wxConfigService.query(cnd);
		map.put("wxList", wxList);
		return map;
	}
	
	
	/**
	 * 获取微信公众号服务
	 * 
	 * @param wxid
	 * @return
	 */
	public WxMpService getWxMpService(String wxid) {
		WxMpConfigStorage config = getWxConfig(wxConfigService.fetch(wxid));
		WxMpService wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(config);
		return wxMpService;
	}
	/**
	 * 获取公众号配置
	 * 
	 * @param appInfo
	 * @return
	 */
	public WxMpConfigStorage getWxConfig(Wx_config appInfo) {
		if (null == appInfo)
			return null;
		WxMpConfigStorage config = new WxMpInMemoryConfigStorage();
		((WxMpInMemoryConfigStorage) config).setAppId(appInfo.getAppid()); // 设置微信公众号的appid
		((WxMpInMemoryConfigStorage) config).setSecret(appInfo.getAppsecret()); // 设置微信公众号的app
		((WxMpInMemoryConfigStorage) config).setToken(appInfo.getToken()); // 设置微信公众号的token
		((WxMpInMemoryConfigStorage) config).setAesKey(appInfo.getEncodingAESKey()); // 设置微信公众号的EncodingAESKey

		return config;
	}

}
